package com.farm.sfile.controller;

import com.farm.sfile.domain.FileBase;
import com.farm.sfile.out.files.WsServer;
import com.farm.sfile.service.FileBaseServiceInter;
import com.farm.wdas.client.WSFClient;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;
import javax.servlet.http.HttpServletRequest;
import javax.annotation.Resource;
import com.farm.web.easyui.EasyUiUtils;

import java.util.Map;
import org.apache.log4j.Logger;

import javax.servlet.http.HttpSession;
import com.farm.core.page.RequestMode;
import com.farm.core.page.OperateType;
import com.farm.core.sql.query.DBRule;
import com.farm.core.sql.query.DataQuery;
import com.farm.core.sql.result.DataResult;
import com.farm.core.sql.result.ResultsHandle;
import com.farm.parameter.FarmParameterService;
import com.farm.core.page.ViewMode;
import com.farm.web.WebUtils;

/* *
 *功能：文件控制层
 *详细：
 *
 *版本：v0.1
 *作者：FarmCode代码工程
 *日期：20150707114057
 *说明：
 */
@RequestMapping("/filebase")
@Controller
public class FileBaseController extends WebUtils {
	private final static Logger log = Logger.getLogger(FileBaseController.class);
	@Resource
	private FileBaseServiceInter fileBaseServiceImpl;

	@RequestMapping("/wdasInfos")
	public ModelAndView wdasInfos(HttpSession session) {
		ViewMode view = ViewMode.getInstance();
		String operatorLoginname = FarmParameterService.getInstance().getParameter("config.wdas.api.loginname");
		String operatorPassword = FarmParameterService.getInstance().getParameter("config.wdas.api.password");
		String secret = FarmParameterService.getInstance().getParameter("config.wdas.secret");
		String serviceUrl = FarmParameterService.getInstance().getParameter("config.wdas.url");
		String guestkey = FarmParameterService.getInstance().getParameter("config.wdas.guestkey");
		WSFClient client = WSFClient.getInstance(operatorLoginname, operatorPassword, secret, serviceUrl, guestkey);
		try {
			client.isAble();
		} catch (Exception e) {
			view.putAttr("ERROR", e.getMessage());
		}
		return view.returnModelAndView("file/WdasInfo");
	}

	/**
	 * 查询结果集合
	 * 
	 * @return
	 */
	@RequestMapping("/query")
	@ResponseBody
	public Map<String, Object> queryall(DataQuery query, HttpServletRequest request) {
		try {
			query = EasyUiUtils.formatGridQuery(request, query);
			if (query.getRule("PSTATE") == null) {
				query.addRule(new DBRule("PSTATE", "9", "!="));
			}
			if (query.getRule("LOADSTATE") == null) {
				query.addRule(new DBRule("LOADSTATE", "9", "!="));
			}
			DataResult result = fileBaseServiceImpl.createFilebaseSimpleQuery(query).search();
			result.runHandle(new ResultsHandle() {
				@Override
				public void handle(Map<String, Object> row) {
					String fileid = (String) row.get("ID");
					Integer num = WsServer.getInstance().getCurrentProcess(fileid);
					if (num > 0 && row.get("LOADSTATE").equals("3")) {
						row.put("LOADSTATE", "同步中(" + num + "%)...");
					}
				}
			});
			result.runDictionary("0:临时,1:持久,2:永久,9:删除", "PSTATE");
			result.runDictionary("0:未负载,1:待负载,2:完成负载,8:负载失败,9:禁止负载,3:同步中...", "LOADSTATE");
			result.runformatTime("CTIME", "yyyy-MM-dd HH:mm:ss");
			return ViewMode.getInstance().putAttrs(EasyUiUtils.formatGridData(result)).returnObjMode();
		} catch (Exception e) {
			log.error(e.getMessage());
			return ViewMode.getInstance().setError(e.getMessage(), e).returnObjMode();
		}
	}

	/**
	 * 提交修改数据
	 * 
	 * @return
	 */
	@RequestMapping("/edit")
	@ResponseBody
	public Map<String, Object> editSubmit(FileBase entity, HttpSession session) {
		// TODO 自动生成代码,修改后请去除本注释
		try {
			entity = fileBaseServiceImpl.editFilebaseEntity(entity, getCurrentUser(session));
			return ViewMode.getInstance().setOperate(OperateType.UPDATE).putAttr("entity", entity).returnObjMode();

		} catch (Exception e) {
			log.error(e.getMessage());
			return ViewMode.getInstance().setOperate(OperateType.UPDATE).setError(e.getMessage(), e).returnObjMode();
		}
	}

	/**
	 * 提交新增数据
	 * 
	 * @return
	 */
	@RequestMapping("/add")
	@ResponseBody
	public Map<String, Object> addSubmit(FileBase entity, HttpSession session) {
		// TODO 自动生成代码,修改后请去除本注释
		try {
			entity = fileBaseServiceImpl.insertFilebaseEntity(entity, getCurrentUser(session));
			return ViewMode.getInstance().setOperate(OperateType.ADD).putAttr("entity", entity).returnObjMode();
		} catch (Exception e) {
			log.error(e.getMessage());
			return ViewMode.getInstance().setOperate(OperateType.ADD).setError(e.getMessage(), e).returnObjMode();
		}
	}

	/**
	 * 删除数据
	 * 
	 * @return
	 */
	@RequestMapping("/del")
	@ResponseBody
	public Map<String, Object> delSubmit(String ids, HttpSession session) {
		try {
			for (String id : parseIds(ids)) {
				fileBaseServiceImpl.deleteFilebaseEntity(id, getCurrentUser(session));
			}
			return ViewMode.getInstance().returnObjMode();
		} catch (Exception e) {
			log.error(e.getMessage());
			return ViewMode.getInstance().setError(e.getMessage(), e).returnObjMode();
		}
	}

	/**
	 * 加载到远程文件服务
	 * 
	 * @return
	 */
	@RequestMapping("/loadRemoteFile")
	@ResponseBody
	public Map<String, Object> loadRemoteFile(String ids, HttpSession session) {
		try {
			if (!FarmParameterService.getInstance().getParameter("config.outfile.able").toLowerCase().equals("true")) {
				throw new RuntimeException(
						"远程负载服务未开启！" + FarmParameterService.getInstance().getParameter("config.outfile.able"));
			}
			fileBaseServiceImpl.remoteLoadReady(parseIds(ids));
			return ViewMode.getInstance().returnObjMode();
		} catch (Exception e) {
			log.error(e.getMessage());
			return ViewMode.getInstance().setError(e.getMessage(), e).returnObjMode();
		}
	}

	/**
	 * 加载到远程文件数量
	 * 
	 * @return
	 */
	@RequestMapping("/reloadRemoteFileNum")
	@ResponseBody
	public Map<String, Object> reloadRemoteFileNum(String ids, HttpSession session) {
		try {
			fileBaseServiceImpl.reloadRemoteFileNum(parseIds(ids));
			fileBaseServiceImpl.clearRefreshNum(parseIds(ids));
			return ViewMode.getInstance().returnObjMode();
		} catch (Exception e) {
			log.error(e.getMessage());
			return ViewMode.getInstance().setError(e.getMessage(), e).returnObjMode();
		}
	}

	/**
	 * 逻辑删除数据
	 * 
	 * @return
	 */
	@RequestMapping("/logicdel")
	@ResponseBody
	public Map<String, Object> logicdel(String ids, HttpSession session) {
		try {
			for (String id : parseIds(ids)) {
				fileBaseServiceImpl.deleteFileByLogic(id, getCurrentUser(session));
			}
			return ViewMode.getInstance().returnObjMode();
		} catch (Exception e) {
			log.error(e.getMessage());
			return ViewMode.getInstance().setError(e.getMessage(), e).returnObjMode();
		}
	}

	@RequestMapping("/list")
	public ModelAndView index(HttpSession session) {
		return ViewMode.getInstance().returnModelAndView("file/FileBaseResult");
	}

	@RequestMapping("/resources")
	public ModelAndView resources(String fileid, HttpSession session) {
		try {
			FileBase file = fileBaseServiceImpl.getFilebaseEntity(fileid);
			return ViewMode.getInstance().putAttr("RESOURCES", WsServer.getInstance().getResources(file.getId()))
					.returnModelAndView("file/FileBaseResource");
		} catch (Exception e) {
			log.error(e.getMessage());
			return ViewMode.getInstance().setError(e + e.getMessage(), e).returnModelAndView("file/FileBaseResource");
		}
	}

	/**
	 * 显示详细信息（修改或浏览时）
	 *
	 * @return
	 */
	@RequestMapping("/form")
	public ModelAndView view(RequestMode pageset, String ids) {
		try {
			ViewMode view = ViewMode.getInstance();
			switch (pageset.getOperateType()) {
			case (0): {// 查看
				return view.putAttr("pageset", pageset).putAttr("realpath", fileBaseServiceImpl.getFileRealPath(ids))
						.putAttr("entity", fileBaseServiceImpl.getFilebaseEntity(ids))
						.returnModelAndView("file/FileBaseForm");
			}
			case (1): {// 新增
				return view.putAttr("pageset", pageset).returnModelAndView("file/FileBaseForm");
			}
			case (2): {// 修改
				return view.putAttr("pageset", pageset).putAttr("entity", fileBaseServiceImpl.getFilebaseEntity(ids))
						.returnModelAndView("file/FileBaseForm");
			}
			default:
				break;
			}
			return ViewMode.getInstance().returnModelAndView("file/FileBaseForm");
		} catch (Exception e) {
			return ViewMode.getInstance().setError(e + e.getMessage(), e).returnModelAndView("file/FileBaseForm");
		}
	}

	/**
	 * 显示详细信息（修改或浏览时）
	 *
	 * @return
	 */
	@RequestMapping("/viewText")
	public ModelAndView viewText(String id) {
		try {
			ViewMode view = ViewMode.getInstance();
			return view.returnModelAndView("file/FileTextView");
		} catch (Exception e) {
			return ViewMode.getInstance().setError(e + e.getMessage(), e).returnModelAndView("file/FileTextView");
		}
	}
}
